package com.hospital.controller;

import com.google.gson.Gson;
import com.hospital.dao.impl.PatientDao;
import com.hospital.model.DoctorView;
import com.hospital.model.Patient;
import com.hospital.util.LoggerUtil;
import org.slf4j.Logger;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 我的患者管理Servlet
 * 处理医生查看和管理其负责的患者信息的请求
 */
@WebServlet("/myPatients/*")
public class MyPatientsServlet extends HttpServlet {
    /** 患者数据访问对象，用于处理患者信息的数据库操作 */
    private PatientDao patientDao = new PatientDao();
    
    /** JSON转换工具对象，用于处理JSON数据的序列化和反序列化 */
    private Gson gson = new Gson();

    /**
     * 处理获取患者信息的GET请求
     * 支持以下功能：
     * /detail/{patientId} - 获取指定患者的详细信息
     * /?searchName={name} - 根据患者姓名搜索
     * / - 获取医生负责的所有患者列表
     * 
     * @param req HTTP请求对象
     * @param resp HTTP响应对象
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        
        resp.setContentType("application/json;charset=UTF-8");
        String pathInfo = req.getPathInfo();
        
        // 从session获取当前登录的医生信息
        HttpSession session = req.getSession();
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        
        if (doctor == null) {
            resp.setStatus(401);
            resp.getWriter().write("{\"error\": \"未登录\"}");
            return;
        }
        
        // 处理获取病人详情的请求
        if (pathInfo != null && pathInfo.startsWith("/detail/")) {
            String patientIdStr = pathInfo.substring("/detail/".length());
            try {
                Integer patientId = Integer.parseInt(patientIdStr);
                Map<String, Object> patientDetail = patientDao.getPatientDetail(patientId);
                resp.getWriter().write(gson.toJson(patientDetail));
                return;
            } catch (NumberFormatException e) {
                resp.setStatus(400);
                resp.getWriter().write("{\"error\": \"无效的病人ID\"}");
                return;
            }
        }
        
        // 处理获取病人列表的请求
        String searchName = req.getParameter("searchName");
        List<Patient> patients;
        
        if (searchName != null && !searchName.trim().isEmpty()) {
            patients = patientDao.searchPatientsByName(doctor.getDoctorId(), searchName);
        } else {
            patients = patientDao.getPatientsByDoctorId(doctor.getDoctorId());
        }
        
        resp.getWriter().write(gson.toJson(patients));
    }
} 